package org.huntaway.kindergarten.manager;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.huntaway.kernel.NutException;
import org.huntaway.kindergarten.po.ClassInfo;
import org.huntaway.kindergarten.po.Genearch;
import org.huntaway.kindergarten.po.Student;
import org.huntaway.kindergarten.po.Teacher;
import org.huntaway.kindergarten.util.EnumUse;
import org.huntaway.kindergarten.util.GlobalCon;
import org.huntaway.kindergarten.util.PageResult;

public class StudentMng extends BaseMng<Student> {
	ClassInfoMng clMng = (ClassInfoMng) sm.getMng(GlobalCon.CLASS_INFO);
	TeacherMng tMng = (TeacherMng) sm.getMng(GlobalCon.TEACHER);
	GenearchMng genearMng = (GenearchMng) sm.getMng(GlobalCon.GENEARCH);

	@SuppressWarnings("unchecked")
	public List<Student> getStudent() {
		return dateManage.findbyhql("from Student").list();
	}
	public PageResult list(PageResult pageResult,Student item) {
		Criteria studentCri = dateManage.createCriteria(Student.class);
		studentCri.addOrder(Order.asc("id"));
		return super.getRes(pageResult,studentCri);
	}
	public PageResult query(PageResult pageResult,Student item) {
		Criteria studentCri = dateManage.createCriteria(Student.class);
		if (item.getTName() != null && !item.equals("")) {
			studentCri.add(Expression.like("TName", item.getTName()));
		}
		studentCri.addOrder(Order.asc("id"));
		return super.getRes(pageResult,studentCri);
	}

	public void save(Student item) {
		item.setIsuse(EnumUse.NO.getValue());
		updateEntityUse(item);
		super.save(item);
	}
	public void update(Student item) {
		updateEntityUse(item);		
		super.update(item);
	}
	private void updateEntityUse(Student item) {
		if (item.getClassInfo() != null) {
			ClassInfo classInfo = clMng.getEntityById(item.getClassInfo()
					.getClass(), item.getClassInfo().getId());
			item.setIsuse(EnumUse.YES.getValue());
			clMng.save(classInfo);
		}
		if (item.getTeacher() != null) {
			Teacher teacher = tMng.getEntityById(item.getTeacher().getClass(),
					item.getTeacher().getId());
			teacher.setIsuse(EnumUse.YES.getValue());
			tMng.save(teacher);
		}
		if (item.getGenearch() != null) {
			Genearch genearch = genearMng.getEntityById(item.getGenearch()
					.getClass(), item.getGenearch().getId());
			genearch.setIsuse(EnumUse.YES.getValue());
			genearMng.save(genearch);
		}
	}
	public void delete(Student item) throws NutException {
		if(item.getIsuse().intValue()==EnumUse.YES.getValue()){
			throwException(item);
		}
		super.delete(item);
	}
}
